package com.ada.mqtt;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class App {

    public static void main(String[] args) throws MqttException, InterruptedException {

        String broker = "tcp://127.0.0.1:1883";
        String clientId = "YourClientId"; // 客户端唯一标识

        MqttClient client = new MqttClient(broker, clientId, new MemoryPersistence());


        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true); // 清除会话
        //connOpts.setUserName("YourUsername"); // 用户名
        //connOpts.setPassword("YourPassword".toCharArray()); // 密码

        client.connect(connOpts);

        for (int i = 0; i < 100; i++) {
            String topic = "topic/to/subscribe";
            String message = "Hello, MQTT!";
            client.publish(topic, message.getBytes(), 0, false);
            Thread.sleep(100);
        }


        //client.close();
        String topic1 = "topic/to/subscribe";
        client.subscribe(topic1);

    }
}
